package com.pri.chat.activity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.StatusBarUtil;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.DTBean;
import com.netease.nim.uikit.net.entity.MessageBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.MainActivity;
import com.pri.chat.R;
import com.pri.chat.adapter.MessageAdapter;
import com.pri.chat.dialog.DialogUtil;
import com.pri.chat.model.EvaListModel;
import com.pri.chat.model.MessageModel;
import com.pri.chat.model.SayModel;
import com.pri.chat.model.ZanModel;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.FriendsCircleImageLayout;
import com.pri.chat.utils.GlideEngine;
import com.pri.chat.utils.GlideUtil;
import com.pri.chat.utils.StringUtils;
import com.pri.chat.utils.TimeUtils;
import com.pri.chat.view.ImageViewPlus;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxDataTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogSureCancel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/8
 */
public class DTmsgActivity extends AppCompatActivity {
    private static final String TAG = "DTmsgActivity";
    @BindView(R.id.backBtn)
    ImageView backBtn;
    @BindView(R.id.iv_logo)
    ImageViewPlus ivLogo;
    @BindView(R.id.tv_dt_name)
    TextView tvDtName;
    @BindView(R.id.sex_bg)
    View sex_bg;
    @BindView(R.id.sex_logo)
    ImageView sex_logo;
    @BindView(R.id.tv_dt_age)
    TextView tvDtAge;
    @BindView(R.id.tv_say_hello)
    TextView tvSayHello;
    @BindView(R.id.tv_zl_num)
    TextView tv_zl_num;


    @BindView(R.id.tv_dt_desc)
    TextView tvDtDesc;
    @BindView(R.id.circle_layout)
    FriendsCircleImageLayout circleLayout;

    @BindView(R.id.zanLogo)
    ImageView zanLogo;
    @BindView(R.id.zanNum)
    TextView zanNum;
    @BindView(R.id.zanLinear)
    View tvDtZan;

    @BindView(R.id.plNum)
    TextView plNum;
    @BindView(R.id.plLinear)
    View plLinear;

    @BindView(R.id.shareBtn)
    ImageView shareBtn;
    @BindView(R.id.rec_comment)
    RecyclerView recComment;
    @BindView(R.id.iv_none)
    ImageView ivNone;
    @BindView(R.id.srl_main)
    SmartRefreshLayout srlMain;
    @BindView(R.id.et_input)
    EditText etInput;
    @BindView(R.id.tv_send_message)
    TextView tvSendMessage;
    @BindView(R.id.nsv)
    NestedScrollView nsv;

    @BindView(R.id.vip_bg)
    TextView vip_bg;
    @BindView(R.id.vip_super_bg)
    TextView vip_super_bg;


    @BindView(R.id.time_address_look)
    TextView time_address_look;

    private String id;
    private DTBean dtBean;
    private int position;
    private MessageAdapter mAdapter;
    private List<MessageBean> mList;
    private int page = 1;
    private boolean isShowDialog = true;
    private Context mContext;

    private MyReceiver myReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dt_msg_layout);
        mContext = this;
        View view = findViewById(R.id.titleRelate);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.white), 0);
        StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, view);
        StatusBarUtil.setLightMode(this);
        ButterKnife.bind(this);
        id = getIntent().getExtras().getString("id");
        dtBean = getIntent().getExtras().getParcelable("dt");
        if(dtBean == null){
            getDongTai();
        }else{
            initRec();
            initMsg();
            initData();
            initSrl();
        }
//        initLayout();

        IntentFilter filter = new IntentFilter();
        filter.addAction(MainActivity.UPDATE_DACALL);
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(myReceiver);
    }

    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(MainActivity.UPDATE_DACALL.equals(intent.getAction())){
                //更新动态
                String memberId = intent.getExtras().getString("memberId");
                int sfdc = intent.getExtras().getInt("sfdc");
                if(dtBean.getMemberId().equals(memberId)){
                    dtBean.setSfdc(sfdc);
                    tvSayHello.setBackgroundResource(R.drawable.btn_gray30_shape);
                }
            }
        }
    }



    private Dialog mShareDialog;

    private void initShareDialog(String path) {
        mShareDialog = DialogUtil.getInstance().showShareDialog(this,1);
        DialogUtil.getInstance().setOnShareClickListener(new DialogUtil.OnShareClickListener() {
            @Override
            public void qqOnClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("id",dtBean.getId());
                bundle.putString("image",path);
                bundle.putString("title",dtBean.getMemberName());
                bundle.putString("content",dtBean.getContent());
                RxActivityTool.skipActivity(mContext, ShareMemberActivity.class,bundle);
                mShareDialog.dismiss();mShareDialog.dismiss();
            }

            @Override
            public void circleOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWechatMoments(path,HttpMethods.SHARE_TITLE,dtBean.getContent(),HttpMethods.SHARE_URL);
            }

            @Override
            public void qZoneOnClick(View v) {
                mShareDialog.dismiss();
                //删除操作
                deleteDongTai();
            }

            @Override
            public void weixinOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWeChat(path,HttpMethods.SHARE_TITLE,dtBean.getContent(),HttpMethods.SHARE_URL);
            }

            @Override
            public void jubaoOnClick(View v) {
                mShareDialog.dismiss();
                Bundle bundle = new Bundle();
                bundle.putString("id",id);
                bundle.putString("type","0");
                RxActivityTool.skipActivity(mContext, ReleaseJuBaoAcctivity.class,bundle);
            }
        });
        mShareDialog.show();
    }

    private void deleteDongTai() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            if (baseBean.isSuccess()) {
                RxToast.normal("删除成功！");
                sendBroadcastToMain(2);
            }
        };

        Map<String, Object> params = new HashMap<>();
        params.put("id", mList.get(position).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().deleteDongTai(new ProgressSubscriber<>(onNextListener, mContext, false), requestBody);
    }

    private void initSrl() {
        srlMain.setOnRefreshListener(refresh_layout -> {
            refresh_layout.finishRefresh(1000);
            refresh();
        });
        srlMain.setOnLoadmoreListener(refresh_layout -> {
            refresh_layout.finishLoadmore(1000);
            isShowDialog = false;
            page++;
            initData();
        });
    }

    private void refresh() {
        page = 1;
        isShowDialog = false;
        mList.clear();
        mAdapter.notifyDataSetChanged();
        initData();
    }

//    private void initLayout() {
//        nsv.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (nestedScrollView, i, i1, i2, i3) -> {
//            if (llHuifu.getVisibility() != View.GONE) {
//                llHuifu.setVisibility(View.GONE);
//                View view = getCurrentFocus();
//                HideSoftInput(view.getWindowToken());
//            }
//        });
//    }

    private void initRec() {
        mList = new ArrayList<>();
        LinearLayoutManager linear = new LinearLayoutManager(this);
//        recComment.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST));
        recComment.setLayoutManager(linear);
        recComment.setNestedScrollingEnabled(false);
        mAdapter = new MessageAdapter(R.layout.item_message, mList);
        recComment.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_logo:
                        Bundle bundle = new Bundle();
                        bundle.putString("id", mList.get(position).getMemberId());
                        RxActivityTool.skipActivity(DTmsgActivity.this, OtherPeopleMsgActivity.class, bundle);
                        break;
                }
            }
        });

        mAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int pos) {
                if (SharedHelper.readId(mContext).equals(mList.get(pos).getMemberId()) || SharedHelper.readId(mContext).equals(dtBean.getMemberId())) {
                    //弹出删除提示；
                    initDialog("确定删除该评论？", pos);
                }
                return false;
            }
        });

    }

    private void initDialog(String content, int pos) {
        RxDialogSureCancel rxDialogEditSureCancel = new RxDialogSureCancel(mContext);
        rxDialogEditSureCancel.getLogoView().setVisibility(View.GONE);
        rxDialogEditSureCancel.getTitleView().setTextSize(18);
        rxDialogEditSureCancel.getTitleView().setTextColor(Color.BLACK);
        rxDialogEditSureCancel.setTitle("提示");
        rxDialogEditSureCancel.setContent(content);
        rxDialogEditSureCancel.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rxDialogEditSureCancel.dismiss();
            }
        });
        rxDialogEditSureCancel.setSureListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rxDialogEditSureCancel.dismiss();
                delPingLun(mList.get(pos).getId(), pos);
            }
        });
        rxDialogEditSureCancel.show();
    }

    /**
     * 删除评论
     */
    private void delPingLun(String pingLunId, int pos) {
        SubscriberOnNextListener<BaseBean<List<BaseBean>>> onNextListener = baseBean -> {
            RxToast.normal(baseBean.getMsg());
            if (baseBean.isSuccess()) {
                mList.remove(pos);
                mAdapter.notifyItemRemoved(pos);
                dtBean.setPlNum((Integer.parseInt(dtBean.getPlNum()) - 1) + "");
                plNum.setText(dtBean.getPlNum());
                tv_zl_num.setText("最新评论(" + dtBean.getPlNum() + ")");
                sendBroadcastToMain(1);
            }
        };

        Map<String, Object> params = new HashMap<>();
        params.put("pingLunId", pingLunId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().delPingLun(new ProgressSubscriber<>(onNextListener, this, isShowDialog), requestBody);
    }


    private void initMsg() {
        if (dtBean.getSfdz() == 0) {
            zanLogo.setImageResource(R.mipmap.ic_zan_gray_normal);
        } else {
            zanLogo.setImageResource(R.mipmap.ic_zan_selected);
        }

        tvDtAge.setText(dtBean.getAge());
        tvDtName.setText(dtBean.getMemberName());
        tvDtDesc.setText(dtBean.getContent());
        zanNum.setText(dtBean.getZanNum() + "");
        plNum.setText(dtBean.getPlNum() + "");
        tv_zl_num.setText("最新评论(" + dtBean.getPlNum() + ")");
        GlideUtil.getInstance().loadHeadImg(this, ivLogo, dtBean.getHeadPic());
        if (!RxDataTool.isEmpty(dtBean.getPicList())) {
            String imgs[] = dtBean.getPicList().split(",");
            List<String> list = new ArrayList<>();
            List<LocalMedia> mediaList = new ArrayList<>();
            for (int j = 0; j < imgs.length; j++) {
                LocalMedia localMedia = new LocalMedia();
                list.add(imgs[j]);
                localMedia.setPath(imgs[j]);
                mediaList.add(localMedia);

            }
            dtBean.setImgs(list);
            dtBean.setMediaList(mediaList);

            circleLayout.setImageUrls(dtBean.getImgs());
            circleLayout.setSpacing(10f);
            circleLayout.setOnItemClickListener((view, position) -> {
                PictureSelector.create(this)
                        .themeStyle(R.style.picture_default_style)
                        .isNotPreviewDownload(true)
                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                        .openExternalPreview(position, dtBean.getMediaList());
            });
        }

        if ("男".equals(dtBean.getSex())) {
            sex_logo.setImageResource(R.mipmap.man);
            sex_bg.setBackgroundResource(R.drawable.btn_sex_man);
        } else {
            sex_logo.setImageResource(R.mipmap.woman);
            sex_bg.setBackgroundResource(R.drawable.btn_sex_woman);
        }
        if ("是".equals(dtBean.getMemberLevel())) {
            vip_bg.setVisibility(View.VISIBLE);
            vip_bg.setText("VIP");
        } else {
            vip_bg.setVisibility(View.GONE);
        }
        if ("是".equals(dtBean.getMemberLevel())) {
            vip_super_bg.setVisibility(View.VISIBLE);
            vip_super_bg.setText("SVIP");
        } else {
            vip_super_bg.setVisibility(View.GONE);
        }

        if (dtBean.getSfdc() == 0) {
            tvSayHello.setBackgroundResource(R.drawable.btn_orange_gradient_shape);
        } else {
            tvSayHello.setBackgroundResource(R.drawable.btn_gray30_shape);
        }

        String info = TimeUtils.computeFromNowStr(dtBean.getAddDate());
        if (!StringUtils.isEmpty(dtBean.getCity())) {
            info += " · " + dtBean.getCity();
        }
        info += " · " + dtBean.getReadNum() + "人看过";
        time_address_look.setText(info);
    }

    // 隐藏软键盘
    private void HideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void initData() {
        SubscriberOnNextListener<BaseBean<List<MessageBean>>> onNextListener = baseBean -> {
            if (baseBean.getData().isEmpty() && page == 1) {
                ivNone.setVisibility(View.VISIBLE);
                mAdapter.notifyDataSetChanged();

            } else {
                ivNone.setVisibility(View.INVISIBLE);
                mList.addAll(baseBean.getData());
                mAdapter.notifyDataSetChanged();
            }
        };

        EvaListModel evaListModel = new EvaListModel();
        evaListModel.setPageIndex(page);
        evaListModel.setObjId(dtBean.getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(evaListModel));
        HttpMethods.getInstance().listPingLun(new ProgressSubscriber<>(onNextListener, this, isShowDialog), requestBody);
    }

    private void getDongTai() {
        SubscriberOnNextListener<BaseBean<DTBean>> onNextListener = baseBean -> {
            if(baseBean.isSuccess()){
                dtBean = baseBean.getData();
                initRec();
                initMsg();
                initData();
                initSrl();
            }
        };

        Map<String,Object> params = new HashMap<>();
        params.put("memberId",SharedHelper.readId(mContext));
        params.put("otherMemberId",id);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().getDongTaiById(new ProgressSubscriber<>(onNextListener, this, isShowDialog), requestBody);
    }

    @OnClick({R.id.backBtn, R.id.shareBtn, R.id.zanLinear, R.id.iv_logo, R.id.plLinear, R.id.tv_say_hello, R.id.tv_send_message})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backBtn:
                finish();
                break;
            case R.id.shareBtn:
                if (!dtBean.getImgs().get(0).isEmpty()) {
                    initShareDialog(dtBean.getImgs().get(0));
                } else {
                    initShareDialog("");
                }
                break;
            case R.id.zanLinear:
                httpLike();
                break;
            case R.id.iv_logo:
                Bundle bundle = new Bundle();
                bundle.putString("id", dtBean.getMemberId());
                RxActivityTool.skipActivity(this, OtherPeopleMsgActivity.class, bundle);
                break;
            case R.id.plLinear:
//                llHuifu.setVisibility(View.VISIBLE);
//                etInput.setFocusable(true);
//                etInput.setFocusableInTouchMode(true);
//                etInput.requestFocus();
//                etInput.clearFocus();//失去焦点
//                etInput.requestFocus();//获取焦点
//                ShowKeyboard();
                break;
            case R.id.tv_say_hello:
                if (dtBean.getSfdc() == 1) {
                    return;
                }
                if (SharedHelper.readId(this).equals(dtBean.getMemberId())) {
                    RxToast.normal("不能给自己打招呼");
                } else {
                    httpSayHello();
                }
                break;
            case R.id.tv_send_message:
                if (etInput.getText().toString().isEmpty()) {
                    RxToast.normal("请输入回复内容");
                    return;
                }

                sendMessage();
                break;
        }
    }

    public void sendBroadcastToMain(int type) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        if (type == 0) {
            //打招呼
            intent.setAction(MainActivity.UPDATE_DACALL);
            bundle.putString("memberId", dtBean.getMemberId());
            bundle.putInt("sfdc", dtBean.getSfdc());
        } else if(type == 1) {
            intent.setAction(MainActivity.UPDATE_DONGTAI);
            bundle.putParcelable("dtObj", dtBean);
        }else{
            intent.setAction(MainActivity.DELETE_DONGTAI);
            bundle.putParcelable("dtObj", dtBean);
        }
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }

    private void httpSayHello() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("打招呼成功");
            tvSayHello.setBackgroundResource(R.drawable.btn_gray30_shape);
            dtBean.setSfdc(1);
            sendBroadcastToMain(0);
        };
        SayModel userModel = new SayModel();
        userModel.setMemberId(SharedHelper.readId(this));
        userModel.setOtherMemberId(dtBean.getMemberId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().callMember(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    private void httpLike() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            Log.d(TAG, "onNext: " + baseBean.toString());
            if (dtBean.getSfdz() == 0) {
                dtBean.setSfdz(1);
                dtBean.setZanNum(dtBean.getZanNum() + 1);
                zanNum.setText(String.valueOf(dtBean.getZanNum()));
                zanLogo.setImageResource(R.mipmap.ic_zan_selected);
            } else {
                dtBean.setSfdz(0);
                dtBean.setZanNum(dtBean.getZanNum() - 1);
                zanNum.setText(String.valueOf(dtBean.getZanNum()));
                zanLogo.setImageResource(R.mipmap.ic_zan_gray_normal);
            }
            sendBroadcastToMain(1);
            RxToast.normal(baseBean.getMsg());
        };
        ZanModel zanModel = new ZanModel();
        zanModel.setBdzId(dtBean.getId());
        zanModel.setDzrId(SharedHelper.readId(this));
        zanModel.setType(0);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(zanModel));
        HttpMethods.getInstance().saveDianZan(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }

    //显示虚拟键盘
    private void ShowKeyboard() {
        InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

    }

    private void sendMessage() {
        SubscriberOnNextListener<BaseBean<List<MessageBean>>> onNextListener = baseBean -> {
            RxToast.normal("评论成功");
            etInput.setText("");
            dtBean.setPlNum((Integer.parseInt(dtBean.getPlNum()) + 1) + "");
            tv_zl_num.setText("最新评论(" + dtBean.getPlNum() + ")");
            plNum.setText(dtBean.getPlNum() + "");
            sendBroadcastToMain(1);
            refresh();
        };
        MessageModel circleEnity = new MessageModel();
        circleEnity.setType(0);
        circleEnity.setObjId(dtBean.getId());
        circleEnity.setMemberId(SharedHelper.readId(this));
        circleEnity.setContent(etInput.getText().toString());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(circleEnity));
        HttpMethods.getInstance().savePingLun(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }
}
